package com.tungse.study.itreator_mode;

import java.io.*;
import java.nio.file.Files;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;

/**
 * @author Tungse
 * 缺少自动关闭bufferedReader 的逻辑
 *
 */
public class UserBatchFile implements Iterable<UserOne>{
    private final File file;
    private final BufferedReader reader;

    public UserBatchFile(File file) {
        this.file = file;
        try {
            this.reader = new BufferedReader(new FileReader(file.getPath()));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Iterator<UserOne> iterator() {
        return new UserBatchFileIterator();
    }

    class UserBatchFileIterator implements Iterator<UserOne> {

        private String userOneStr;

        @Override
        public boolean hasNext() {
            try {
                userOneStr = reader.readLine();
                return userOneStr != null;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public UserOne next() {
            if (userOneStr == null) {
                throw new NoSuchElementException();
            } else {
                String substring = userOneStr.substring(1, userOneStr.length() - 1);
                String[] split = substring.split(",");
                return new UserOne(split[0], Integer.parseInt(split[1]));
            }
        }
    }
}
